<?php 
namespace app\api\controller;
use think\Db;
use think\facade\Session;
class Books extends Base{

	public function getList(){
		$page = $this->request->param('currentPage',1);
		$limit = $this->request->param('pageSize',10);
		$user = db('user')->where('id = '.$this->user['id'])->find();
		$where = NULL;
		if($user['books_ids']){
			$ids = substr($user['books_ids'],1,strlen($user['books_ids'])-1);
			$where = 'id IN('.$ids.')';
		}else{
			$data['status'] = 1;
			$data['data'] = [];
			$data['count'] = 0;

			return returnJson(200,$data);
		}
		$list = db('books')->where($where)->page($page,$limit)->order(['create_time','id'=>'asc'])->select();
		$count = db('books')->where($where)->count();
		// $list = db('books')->page($page,$limit)->order(['create_time','id'=>'asc'])->select();

		foreach ($list as $key => $value) {
			$list[$key]['create_time_str'] = date("Y-m-d H:i:s",$value['create_time']);
		}
		$data['status'] = 1;
		$data['data'] = $list;
		$data['count'] = $count;

		return returnJson(200,$data);
	}

	public function add(){
		if( $this->request->isPost() || $this->request->isAjax() ){
			$user = Session::get('user');
			if( $user ){
				$add['code'] = $this->request->param('code','trim');
				$add['name'] = $this->request->param('name','trim');
				$add['create_time'] = time();
				Db::startTrans();
				try{
					$id = Db::table('books')->insertGetId($add);
					if($id > 0){
						$userInfo = db('user')->where('id = '.$user['id'])->find();
						$userInfo['books_ids'] = $userInfo['books_ids'].','.$id;
						$upd['books_ids'] = $userInfo['books_ids'];
						$upd['id'] = $user['id'];
						$res = Db::table('user')->update($upd);
						if($res !== false){
							Db::commit();
							$data['status'] = 1;
							$data['msg'] = '添加成功！';
							return returnJson(200,$data);
						}else{
							Db::rollback();
							$data['status'] = 0;
							$data['msg'] = '添加失败！';
							return returnJson(200,$data);
						}
					}else{
						Db::rollback();
						$data['status'] = 0;
						$data['msg'] = '添加失败！';
						return returnJson(200,$data);
					}
				}catch(\ErrorException $e){
					Db::rollback();
					$data['status'] = 0;
					$data['msg'] = '添加失败！';
					return returnJson(200,$data);
				}
			}else{
				return returnJson(201,[],'用户信息过期了，请重新登录！');
			}
		}
	}

	public function edit(){
		if( $this->request->isPost() || $this->request->isAjax() ){
			$upd['id'] = $this->request->param('id','trim');
			$upd['code'] = $this->request->param('code','trim');
			$upd['name'] = $this->request->param('name','trim');

			$res = db('books')->update($upd);
			if($res !== false){
				$data['status'] = 1;
				$data['msg'] = '修改成功！';
				return returnJson(200,$data);
			}else{
				$data['status'] = 0;
				$data['msg'] = '修改失败！';
				return returnJson(200,$data);
			}
		}
	}
}